package service

import (
	"dataaysn/internal/model"
	"dataaysn/internal/repository"
	"strconv"

	"github.com/gin-gonic/gin"
)

type MappingRuleService struct {
	repo repository.MappingRuleRepository
}

func NewMappingRuleService(repo repository.MappingRuleRepository) *MappingRuleService {
	return &MappingRuleService{repo: repo}
}

func (s *MappingRuleService) CreateRule(c *gin.Context) {
	var rule model.MappingRule
	if err := c.ShouldBindJSON(&rule); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}

	if err := s.repo.CreateRule(&rule); err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}

	c.JSON(200, rule)
}

func (s *MappingRuleService) GetRule(c *gin.Context) {
	id := c.Param("id")
	rule, err := s.repo.GetRule(id)
	if err != nil {
		c.JSON(404, gin.H{"error": "not found"})
		return
	}
	c.JSON(200, rule)
}

func (s *MappingRuleService) UpdateRule(c *gin.Context) {
	id := c.Param("id")
	var rule model.MappingRule
	if err := c.ShouldBindJSON(&rule); err != nil {
		c.JSON(400, gin.H{"error": err.Error()})
		return
	}
	uintID, err := strconv.ParseUint(id, 10, 32)
	if err != nil {
		// 转换失败，返回错误响应
		c.JSON(400, gin.H{"error": "invalid id format"})
		return
	}
	rule.ID = uint(uintID) // 确保ID正确设置在config中，以便在更新时使用正确的ID
	if err := s.repo.UpdateRule(&rule); err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}

	c.JSON(200, rule)
}

func (s *MappingRuleService) DeleteRule(c *gin.Context) {
	id := c.Param("id")
	if err := s.repo.DeleteRule(id); err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}
	c.JSON(200, gin.H{"message": "deleted"})
}

func (s *MappingRuleService) ListRules(c *gin.Context) {
	rules, err := s.repo.ListRules()
	if err != nil {
		c.JSON(500, gin.H{"error": err.Error()})
		return
	}
	c.JSON(200, rules)
}
